#include "industrial_robot_control/config_loader.h"
#include <fstream>
#include "industrial_robot_control/utils/log.h"

namespace IndustrialRobotControl {

ConfigLoader::ConfigLoader() {}

bool ConfigLoader::load(const std::string& file_path) {
    LOG_INFO("Loading configuration from: {}", file_path);
    
    try {
        // 尝试打开并解析YAML文件
        std::ifstream file(file_path);
        if (!file.is_open()) {
            LOG_ERROR("Failed to open config file: {}", file_path);
            return false;
        }
        
        config_ = YAML::Load(file);
        file_path_ = file_path;
        
        LOG_INFO("Configuration loaded successfully");
        return true;
    } catch (const YAML::Exception& e) {
        LOG_ERROR("Error parsing config file: {}", e.what());
        return false;
    } catch (...) {
        LOG_ERROR("Unknown error loading config file");
        return false;
    }
}

bool ConfigLoader::save(const std::string& file_path) {
    try {
        std::ofstream file(file_path);
        if (!file.is_open()) {
            LOG_ERROR("Failed to open file for writing: {}", file_path);
            return false;
        }
        
        file << config_;
        file_path_ = file_path;
        
        LOG_INFO("Configuration saved to: {}", file_path);
        return true;
    } catch (const std::exception& e) {
        LOG_ERROR("Error saving config file: {}", e.what());
        return false;
    }
}

const YAML::Node& ConfigLoader::get_config() const {
    return config_;
}

YAML::Node& ConfigLoader::get_config() {
    return config_;
}

const std::string& ConfigLoader::get_file_path() const {
    return file_path_;
}

} // namespace IndustrialRobotControl
